import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { fromEvent, Subscription, timer } from 'rxjs';
import { debounceTime, tap } from 'rxjs/operators';
import { ECharts, EChartsOption, init } from 'echarts';

@Component({
  selector: 'app-base-chart',
  templateUrl: './base-chart.component.html',
  styleUrls: ['./base-chart.component.scss']
})
export class BaseChartComponent implements OnInit, OnDestroy {

  @Input() option!: EChartsOption;
  @Input() height = '300px';
  @Input() width = '100%';
  @ViewChild('chart', { static: true }) chart!: ElementRef;
  aChart!: ECharts;
  windowResize!: Subscription;
  timer!: Subscription;
  defaultGrid = {
    top: 10,
    right: 10,
    bottom: 30,
    left: 30,
  };
  constructor() { }

  ngOnInit(): void {
    this.setListen();
    this.boxStyleInit();
    if (this.option) {
      this.echartsInit();
    } else {
      this.chart.nativeElement.innerText = '暂无数据';
    }
  }

  ngOnDestroy(): void {
    if (this.windowResize) {
      this.windowResize.unsubscribe();
    }
    if (this.timer) {
      this.timer.unsubscribe();
    }
  }

  boxStyleInit(): void {
    this.chart.nativeElement.style.width = this.width;
    this.chart.nativeElement.style.height = this.height;
  }

  setListen(): void {
    this.windowResize = fromEvent(window, 'resize').pipe(
      debounceTime(200),
      tap(res => {
        this.aChart.resize();
      })
    ).subscribe();
  }

  echartsInit(): void {
    this.aChart = init(this.chart.nativeElement);
    this.aChart.setOption(Object.assign({ grid: this.defaultGrid }, this.option));
    this.timer = timer(400).subscribe(res => {
      this.aChart.resize();
    });
  }

}
